package com.myself.community.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Component
@Slf4j
public class MailClient {
    @Autowired
    private JavaMailSender mailSender;

    //发件人
    @Value("${spring.mail.username}")
    private String from;

    /**
     * 发送邮件
     * @param to   收件人
     * @param subject  主题
     * @param content  内容
     */
    public void sendMail(String to, String subject, String content) {
        try {
            //得到邮件主体对象
            MimeMessage message = mailSender.createMimeMessage();
            //构建邮件主体
            MimeMessageHelper helper = new MimeMessageHelper(message);
            //设置发件人
            helper.setFrom(from);
            //设置收件人
            helper.setTo(to);
            //设置主题
            helper.setSubject(subject);
            //设置内容
            helper.setText(content, true);
            //发送邮件
            mailSender.send(helper.getMimeMessage());
            log.info("邮件发送成功...");
        } catch (MessagingException e) {
            log.error("发送邮件失败:" + e.getMessage());
        }
    }
}
